package com.neu.service.impl;

import com.neu.constant.MaterialTypeEnum;
import com.neu.pojo.Material;
import com.neu.service.FileService;
import com.neu.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service
public class FileServiceImpl implements FileService {


    @Value("${fileSystem.uploadPath}")
    private String uploadPath;

    @Value("${fileSystem.httpUrl}")
    private String httpUrl;

    @Resource
    private MaterialService materialService;

    @Override
    public String uploadFile(MultipartFile multipartFile, Material material) {
        String dir = "unknown/";
        if (MaterialTypeEnum.of(material.getType()) == MaterialTypeEnum.PROJECT) {
            dir = "project/";
        } else if (MaterialTypeEnum.of(material.getType()) == MaterialTypeEnum.ARTICLE) {
            dir = "article/";
        }
        dir = dir + material.getPid();

        // 上传文件,获取url
        String filename = multipartFile.getOriginalFilename();
        String fileSuffix = filename.substring(filename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString()+fileSuffix;
        File targetFile = new File(uploadPath+dir);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try {
            multipartFile.transferTo(new File(targetFile,newFileName));
        } catch (IOException e) {
            log.error("文件上传异常",e);
        }
        // 新增文件记录
        String url = httpUrl + dir+"/"+newFileName;
        material.setSuffix(fileSuffix);
        material.setUrl(url);
        materialService.insertMaterial(material);

        return url;
    }

    @Override
    public String uploadImg(MultipartFile multipartFile) {
        String dir = "image/";
        String filename = multipartFile.getOriginalFilename();
        String fileSuffix = filename.substring(filename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString()+fileSuffix;
        File targetFile = new File(uploadPath+dir);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try {
            multipartFile.transferTo(new File(targetFile,newFileName));
        } catch (IOException e) {
            log.error("文件上传异常",e);
        }
        // 新增文件记录
        String url = httpUrl + dir+newFileName;
        return url;
    }

}
